package com.example.studyaop.config;

import com.example.studyaop.annotation.LogAnnotation;
import com.example.studyaop.vo.LogVO;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;

/**
 * @Author: hanll
 * @ClassName: LogAspect
 * @Date: 2022-11-16 10:40
 * @Version: 1.0
 * @Description:
 */
@Component
@Aspect
public class LogAspect {


    @Around(value = "@annotation(com.example.studyaop.annotation.LogAnnotation)")
    public void aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取签名
        String signature = joinPoint.getSignature().toString();
        String methodName = signature.substring(signature.lastIndexOf(".") + 1, signature.indexOf("("));
        String classType = joinPoint.getTarget().getClass().getName();
        try {
            Class<?> clz = Class.forName(classType);
            Method[] methods = clz.getDeclaredMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(LogAnnotation.class) && method.getName().equals(methodName)) {
                    // 解析
                    LogVO logVO = parseAnnotation(method);
                    // 日志添加
                    System.out.println(logVO);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 解析方法上注解中的值
    public LogVO parseAnnotation(Method method) {
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        if (null == logAnnotation) {
            return null;
        }
        LogVO logVO = new LogVO();
        logVO.setName(logAnnotation.name());
        logVO.setType(logAnnotation.type());
        return logVO;
    }
}
